package com.neusoft.neuiotms.dcom.converter;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.ClassesDTO;
import com.neusoft.neuiotms.dcom.model.ClassItem;
import com.neusoft.neuiotms.dcom.model.Classes;
import com.neusoft.neuiotms.dcom.repository.ClassItemRepository;
import com.neusoft.neuiotms.dcom.repository.ClassesRepository;

@Component
public class ClassesConverter extends AbstractConverter<Classes, ClassesDTO> {

    @Autowired
    private ClassesRepository classesRepository;
    @Autowired
    private ClassItemConverter classItemConverter;
    @Autowired
    private ClassItemRepository classItemRepository;

    @Override
    public Classes toModel(final ClassesDTO dto) {

        Classes model;

        if (dto.isNew()) {
            model = new Classes();
        } else {
            model = this.classesRepository.getOne(dto.getId());
        }

        model.setName(dto.getName());

        final List<ClassItem> items = model.getItems().stream().collect(Collectors.toList());

        items.forEach(k -> {
            model.getItems().remove(k);
            this.classItemRepository.delete(k);
        });

        dto.getItems().stream().map(s -> {
            final ClassItem itemModel = this.classItemConverter.toModel(s);
            itemModel.setClasses(model);
            return itemModel;
        }).forEach(model.getItems()::add);

        return model;
    }

    @Override
    public ClassesDTO toDTO(final Classes model, final boolean forListView) {

        final ClassesDTO dto = new ClassesDTO();

        dto.setId(model.getId());
        dto.setName(model.getName());

        model.getItems().stream().map(s -> this.classItemConverter.toDTO(s)).filter(k -> null != k)
                .forEach(dto.getItems()::add);
        return dto;
    }

}
